/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.common.util;

import com.hsxxherp.key.common.error.ErrorCode;
import com.hsxxherp.key.common.exception.BusinessException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * RSAUtil 工具类
 *
 * @author Mark·虎克 (2486970363@qq.com)
 */
public class RSAUtil {

    private static final String ALGORITHM = "RSA";
    private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
    private static final int KEY_SIZE = 2048;

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * 生成 RSA 密钥对
     *
     * @return 密钥对
     */
    public static KeyPair generateKeyPair() {
        try {
            KeyPairGenerator keyPairGenerator;
            keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM, "BC");
            keyPairGenerator.initialize(KEY_SIZE);
            return keyPairGenerator.generateKeyPair();
        } catch (Exception e) {
            throw new BusinessException("RSA秘钥生成失败", e).setCode(ErrorCode.CODE_100001);
        }

    }

    /**
     * 获取公钥的 Base64 编码字符串
     *
     * @param publicKey 公钥
     * @return 公钥的 Base64 编码字符串
     */
    public static String getPublicKeyStr(PublicKey publicKey) {
        return Base64.getEncoder().encodeToString(publicKey.getEncoded());
    }

    /**
     * 获取私钥的 Base64 编码字符串
     *
     * @param privateKey 私钥
     * @return 私钥的 Base64 编码字符串
     */
    public static String getPrivateKeyStr(PrivateKey privateKey) {
        return Base64.getEncoder().encodeToString(privateKey.getEncoded());
    }

    /**
     * 将 Base64 编码的公钥字符串转换为 PublicKey 对象
     *
     * @param publicKeyStr 公钥的 Base64 编码字符串
     * @return PublicKey 对象
     */
    public static PublicKey getPublicKey(String publicKeyStr) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(publicKeyStr);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory;
            keyFactory = KeyFactory.getInstance(ALGORITHM, "BC");
            return keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
            throw new RuntimeException("RSA 公钥转换失败！", e);
        }
    }

    /**
     * 将 Base64 编码的私钥字符串转换为 PrivateKey 对象
     *
     * @param privateKeyStr 私钥的 Base64 编码字符串
     * @return PrivateKey 对象
     */
    public static PrivateKey getPrivateKey(String privateKeyStr) {
        try {
            byte[] keyBytes = Base64.getDecoder().decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory;
            keyFactory = KeyFactory.getInstance(ALGORITHM, "BC");
            return keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
            throw new RuntimeException("RSA 私钥转换失败！", e);
        }
    }

    /**
     * 使用公钥进行加密
     *
     * @param publicKey 公钥
     * @param data      待加密的数据
     * @return 加密后的 Base64 编码字符串
     */
    public static String encrypt(PublicKey publicKey, String data) {
        try {
            Cipher cipher;
            cipher = Cipher.getInstance(ALGORITHM, "BC");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] encryptedBytes;
            encryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            throw new BusinessException("RSA解密失败", e).setCode(ErrorCode.CODE_100003);
        }

    }

    /**
     * 使用私钥进行解密
     *
     * @param privateKey    私钥
     * @param encryptedData 加密后的 Base64 编码字符串
     * @return 解密后的原始数据
     */
    public static String decrypt(PrivateKey privateKey, String encryptedData) {
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        } catch (Exception e) {
            throw new RuntimeException("RSA 解密失败！", e);
        }

    }

    /**
     * 使用私钥进行签名
     *
     * @param privateKey 私钥
     * @param data       待签名的数据
     * @return 签名后的 Base64 编码字符串
     */
    public static String sign(PrivateKey privateKey, String data) {
        try {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM, "BC");
            signature.initSign(privateKey);
            signature.update(data.getBytes());
            byte[] signBytes = signature.sign();
            return Base64.getEncoder().encodeToString(signBytes);
        } catch (Exception e) {
            throw new RuntimeException("RSA 签名失败！", e);
        }
    }

    /**
     * 使用公钥进行验签
     *
     * @param publicKey 公钥
     * @param data      原始数据
     * @param sign      签名后的 Base64 编码字符串
     * @return 验签结果，true 表示验签通过，false 表示验签失败
     */
    public static boolean verify(PublicKey publicKey, String data, String sign) {
        try {
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM, "BC");
            signature.initVerify(publicKey);
            signature.update(data.getBytes());
            byte[] signBytes = Base64.getDecoder().decode(sign);
            return signature.verify(signBytes);
        } catch (Exception e) {
            throw new RuntimeException("RSA 验签失败！", e);
        }

    }
}